/*
 * Copyright (c) 2015 smarthome.com All rights reserved. 本软件源代码版权归----所有,未经许可不得任意复制与传播.
 */
package com.smarthome.web.property.controller.kuaidiXiyi;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smarthome.common.tools.excel.ReportExportService;
import com.smarthome.core.account.AccountService;
import com.smarthome.core.kuaidiXiyi.SendCourierService;
import com.smarthome.core.operationservicemanager.CompanyExpressService;
import com.smarthome.domain.bean.ShAccount;
import com.smarthome.domain.bean.ShHistoryAccount;
import com.smarthome.domain.bean.ShOrders;
import com.smarthome.domain.common.Result;
import com.smarthome.domain.enums.OrdersPaymentStatus;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.domain.vo.boss.TimeRange;
import com.smarthome.web.property.utils.UserHolder;

/**
 * 
* @ClassName: SendCourierController
* @Description: 发快递controller
* @author cyj
* @date 2016年3月24日 上午10:44:03
*
 */
@Controller
@RequestMapping("/sendCourierController")
public class SendCourierController {

    @Resource
    private SendCourierService sendCourierService;
    
    @Resource
    private CompanyExpressService companyExpressService;
    
    @Resource
    private AccountService accountService;

    /**
     * 
    * @Title: dataGrid
    * @Description: 获取代发快递datagrid
    * @param shOrders
    * @param page
    * @param timeRange
    * @return 
    * DataGrid  
    * @throws
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(ShOrders shOrders, PageHelper page,TimeRange timeRange) {
    	if(timeRange.getStartGmtCreate() != null) {
    		shOrders.addQueryData("startGmtCreate", timeRange.getStartGmtCreate());
		}
		if(timeRange.getEndGmtCreate() != null) {
			shOrders.addQueryData("endGmtCreate", timeRange.getEndGmtCreate());
		}
		if(timeRange.getStartGmtModify() != null) {
			shOrders.addQueryData("startGmtModify", timeRange.getStartGmtModify());
		}
		if(timeRange.getEndGmtModify() != null) {
			shOrders.addQueryData("endGmtModify", timeRange.getEndGmtModify());
		}
    	if(!UserHolder.isSuperResidence()) {
        	shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
    	}
    	shOrders.setOrderType(2);
    	//shOrders.addQueryData("notStatus", new Integer[]{4});
    	return sendCourierService.dataGrid(shOrders, page);
    }

    /**
     * 跳转到添加页面
     * 
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
    	return "/kuaidiXiyi/sendCourierAdd";
    }

    /**
     * 新增
     * @param deviceSupplier
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(HttpServletRequest request,ShOrders shOrders) {
    	if(shOrders.getCompanyId() == null) {
    		return Result.failure("请选择快递点！");
    	}
    	if(StringUtils.isBlank(shOrders.getName())) {
    		return Result.failure("请输入订单名称！");
    	}
    	if(StringUtils.isBlank(shOrders.getSrcMobile())) {
    		return Result.failure("请输入发件人手机号！");
    	}
    	if(StringUtils.isBlank(shOrders.getSrcAreaDetail())) {
    		return Result.failure("请输入发件街道门牌地址！");
    	}
    	if(StringUtils.isBlank(shOrders.getSrcAccountName())) {
    		return Result.failure("请输入发件人名称！");
    	}
    	if(StringUtils.isBlank(shOrders.getDesMobile())) {
    		return Result.failure("请输入收件人手机号！");
    	}
    	if(StringUtils.isBlank(shOrders.getDesAreaDetail())) {
    		return Result.failure("请输入收件街道门牌地址！");
    	}
    	if(StringUtils.isBlank(shOrders.getDesAccountName())) {
    		return Result.failure("请输入收件人名称！");
    	}
    	if(shOrders.getDesAreaId() == null) {
    		return Result.failure("请选择收件地区！");
    	}
    	if(shOrders.getSrcAreaId() == null) {
    		return Result.failure("请选择发件地区！");
    	}
    	if(shOrders.getAmount() == null) {
    		return Result.failure("请选择快递点、收件省份及输入快递重量以确定金额！");
    	}
    	shOrders.setPaymentStatus(OrdersPaymentStatus.DEEPEND.getType());
    	try {
    		shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
    		if(shOrders.getSrcAccountId() == null) {
    			shOrders.setSrcAccountId(UserHolder.getUserId());
    		}
    		Integer result = sendCourierService.add(shOrders);
    		if(result == 1) {
                return Result.success("添加成功！");
    		}else {
    			return Result.failure("添加快递代发失败！");
    		}
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("系统异常，添加快递代发失败！");
        }
    }

    /**
     * 
    * @Title: editPage
    * @Description: 跳转修改页面
    * @param request
    * @param id
    * @return 
    * String  
    * @throws
     */
    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest request, Long id) {
    	ShOrders shOrders = sendCourierService.getDetailById(id);
    	request.setAttribute("shOrders", shOrders);
        return "/kuaidiXiyi/sendCourierEdit";
    }

    /***
     * 修改
     * @param ShOrders
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(ShOrders shOrders) {
    	if(shOrders.getCompanyId() == null) {
    		return Result.failure("请选择快递点！");
    	}
    	if(StringUtils.isBlank(shOrders.getName())) {
    		return Result.failure("请输入订单名称！");
    	}
    	if(StringUtils.isBlank(shOrders.getSrcMobile())) {
    		return Result.failure("请输入发件人手机号！");
    	}
    	if(StringUtils.isBlank(shOrders.getSrcAreaDetail())) {
    		return Result.failure("请输入发件街道门牌地址！");
    	}
    	if(StringUtils.isBlank(shOrders.getSrcAccountName())) {
    		return Result.failure("请输入发件人名称！");
    	}
    	if(StringUtils.isBlank(shOrders.getDesMobile())) {
    		return Result.failure("请输入收件人手机号！");
    	}
    	if(StringUtils.isBlank(shOrders.getDesAreaDetail())) {
    		return Result.failure("请输入收件街道门牌地址！");
    	}
    	if(StringUtils.isBlank(shOrders.getDesAccountName())) {
    		return Result.failure("请输入收件人名称！");
    	}
    	if(shOrders.getDesAreaId() == null) {
    		return Result.failure("请选择收件地区！");
    	}
    	if(shOrders.getSrcAreaId() == null) {
    		return Result.failure("请选择发件地区！");
    	}
    	if(shOrders.getAmount() == null) {
    		return Result.failure("请选择快递点、收件省份及输入快递重量以确定金额！");
    	}
    	if(shOrders.getStatus() == null) {
    		return Result.failure("请选择状态！");
    	}
    	
        try {
        	//ShResidence nowResidence = UserHolder.getCurrentResidence();
    		//shOrders.setSrcAreaId(nowResidence.getAreaId());
    		shOrders.setHandler(UserHolder.getUser().getEmployeeName());
    		if(shOrders.getSrcAccountId() == null) {
    			shOrders.setSrcAccountId(UserHolder.getUserId());
    		}
    		Integer result = sendCourierService.edit(shOrders);
        	if(result == 1) {
                return Result.success("修改成功！");
    		}else {
    			return Result.failure("未找到指定订单，修改失败！");
    		}
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("系统异常，修改失败！");
        }
    }

    /**
     * 
    * @Title: delete
    * @Description: 删除
    * @param id
    * @return 
    * Result  
    * @throws
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(Long id) {
    	try{
    		Integer result = sendCourierService.chengeStatus(id, 4);
    		if(result == 1) {
                return Result.success("删除成功！");
    		}else {
    			return Result.failure("未找到指定订单，删除失败！");
    		}
    	}catch(Exception e) {
    		e.printStackTrace();
    		return Result.success("系统异常，删除失败！");
    	}
    	
    }

    
    /**
     * 
    * @Title: getHistoryAccountInfo
    * @Description: 通过用户id和手机号获取用户信息
    * @param shHistoryAccount
    * @return 
    * ShHistoryAccount  
    * @throws
     */
    @RequestMapping("/getHistoryAccountInfo")
    @ResponseBody
    public ShHistoryAccount getHistoryAccountInfo(ShHistoryAccount shHistoryAccount) {
    	if(StringUtils.isBlank(shHistoryAccount.getMobile())) {
    		return shHistoryAccount;
    	}
    	if(shHistoryAccount.getAccountId() == null) {
    		shHistoryAccount.setAccountId(UserHolder.getUserId());
    	}
    	try {
    		shHistoryAccount = sendCourierService.getHistoryAccountInfo(shHistoryAccount);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	return shHistoryAccount;
    }
    
    /**
     * 
    * @Title: downloadExcel 
    * @Description: 导出excel 
    * @param response
    * @param shOrders
    * @param timeRange
    * @throws IOException
    * void
    * @throws 
    * @author cyj
     */
    @RequestMapping(value = "/downloadExcel", method = { RequestMethod.GET })
    public void downloadExcel(HttpServletResponse response,ShOrders shOrders,TimeRange timeRange) throws IOException {
    	StringBuilder title = new StringBuilder();
    	if(shOrders.getCompanyId() != null) {
    		title.append(companyExpressService.getById(shOrders.getCompanyId()).getName());
    	}
    	title.append("快递代发统计导出");
        List<String> headerNames = new ArrayList<String>();
        headerNames.add("快递单号");
        /*headerNames.add("订单名称");
        headerNames.add("快递类型");*/
        if(shOrders.getCompanyId() == null) {
            headerNames.add("快递公司");
    	}
        headerNames.add("发件人");
        headerNames.add("发件人电话");
        headerNames.add("发件地址");
        headerNames.add("收件人");
        headerNames.add("收件人电话");
        headerNames.add("收件地址");
        headerNames.add("快递费用（元）");
        /*headerNames.add("状态");
        headerNames.add("创建时间");
        headerNames.add("修改时间");*/
        headerNames.add("发件时间");
        List<String> cellNames = new ArrayList<String>();
        cellNames.add("outBizNum");
        /*cellNames.add("name");
        cellNames.add("courierType");*/
        if(shOrders.getCompanyId() == null) {
            cellNames.add("companyName");
    	}
        cellNames.add("srcAccountName");
        cellNames.add("srcMobile");
        cellNames.add("srcAreaDetail");
        cellNames.add("desAccountName");
        cellNames.add("desMobile");
        cellNames.add("desAreaDetail");
        cellNames.add("amount");
        /*cellNames.add("status");
        cellNames.add("gmtCreate");
        cellNames.add("gmtModify");*/
        cellNames.add("sendDate");
        
        if(timeRange.getStartGmtCreate() != null) {
    		shOrders.addQueryData("startGmtCreate", timeRange.getStartGmtCreate());
		}
		if(timeRange.getEndGmtCreate() != null) {
			shOrders.addQueryData("endGmtCreate", timeRange.getEndGmtCreate());
		}
		if(timeRange.getStartGmtModify() != null) {
			shOrders.addQueryData("startGmtModify", timeRange.getStartGmtModify());
		}
		if(timeRange.getEndGmtModify() != null) {
			shOrders.addQueryData("endGmtModify", timeRange.getEndGmtModify());
		}
    	
    	shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
    	shOrders.setOrderType(2);
    	List<Object> datas = new ArrayList<Object>();
    	List<ShOrders> shOrdersList = sendCourierService.getSendCourierDetailList(shOrders);
        
    	if(shOrdersList != null) {
    		int length = shOrdersList.size();
    		ShOrders order = null;
    		Map<String,Object> data = null;
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		Date now = new Date();
    		for(int i = 0;i < length;i++) {
    			order = shOrdersList.get(i);
    			data = new HashMap<String,Object>();
    			data.put("outBizNum", order.getOutBizNum());
    			/*data.put("name", order.getName());
    			if(order.getCourierType() == 1) {
    				data.put("courierType", "普通");
    			}else if(order.getCourierType() == 2) {
    				data.put("courierType", "及时");
    			}else {
    				data.put("courierType", "未知");
    			}*/
    			if(shOrders.getCompanyId() == null) {
        			data.put("companyName", order.getCompanyName());
    	    	}
    			data.put("srcAccountName", order.getSrcAccountName());
    			data.put("srcMobile", order.getSrcMobile());
    			data.put("srcAreaDetail", order.getSrcProvinceName() + order.getSrcCityName() + order.getSrcDistrictName() + order.getSrcAreaDetail());
    			data.put("desAccountName", order.getDesAccountName());
    			data.put("desMobile", order.getDesMobile());
    			data.put("desAreaDetail", order.getDesProvinceName() + order.getDesCityName() + order.getDesDistrictName() + order.getDesAreaDetail());
    			data.put("amount",order.getAmount() != null?(double)order.getAmount()/100:0);
    			/*if(order.getCourierType() == 1) {
        			data.put("status", "待处理");
    			}else if(order.getCourierType() == 2) {
        			data.put("status", "已发件");
    			}else if(order.getCourierType() == 3) {
        			data.put("status", "关闭");
    			}else if(order.getCourierType() == 5) {
        			data.put("status", "已取件");
    			}else {
        			data.put("status", "未知");
    			}
    			data.put("gmtCreate", sdf.format(order.getGmtCreate()));
    			data.put("gmtModify", sdf.format(order.getGmtModify()));*/
    			data.put("sendDate", sdf.format(now));
    			datas.add(data);
    		}
    	}
        
        new ReportExportService().doExportAndDownload(title.toString(), headerNames, cellNames, datas, response);
    }
    
    /**
     * 
    * @Title: getTotalFee 
    * @Description: 获取总费用
    * @param shOrders
    * @return
    * Long
    * @throws 
    * @author cyj
     */
    @RequestMapping("/getTotalFee")
    @ResponseBody
    public Long getTotalFee(ShOrders shOrders) {
    	Long totalFee = null;
    	try {
    		totalFee = sendCourierService.getExpressTotalFee(shOrders);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	return totalFee;
    }

    /**
     * 
    * @Title: getSrcAccountInfo
    * @Description: 根据电话号码获取发件人信息
    * @param account
    * @return 
    * ShAccount  
    * @throws
     */
    @RequestMapping("/getSrcAccountInfo")
    @ResponseBody
    public ShAccount getSrcAccountInfo(String mobile) {
    	ShAccount account = new ShAccount();
    	if(StringUtils.isBlank(mobile)) {
    		return account;
    	}
    	account.setLoginName(mobile);
    	try {
    		List<ShAccount> list = accountService.queryAccounts(account);
        	if(list != null && !list.isEmpty()) {
        		account = list.get(0);
        	}
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	return account;
    }
}